<template>
  <view class="page page-primary page-order">
    <page-header theme="colorful"></page-header>
    <view class="page-content">
      <page-statistic :data="statisticData"></page-statistic>
      <view class="page-search">
        <fui-input v-model="searchValue" borderTop color="#333" radius=16 :borderBottom="false" placeholderStyle="font-size:28rpx" placeholder="请输入商品名称或订单编号"></fui-input>
        <span class="icon iconfont" @click="searchCenter">&#xe628;</span>
      </view>
      <view class="page-parent-tab" v-show="false">
        <fui-tabs :tabs="parentTabs" @change="onChangeParentTab" background="rgba(0,0,0,0)" size="32" color='#666666' sliderRadius=-1 :center='true' fontWeight='bold' selectedSize='32' selectedColor='var(--fui-color-primary)' scale='1' sliderHeight='8' selectedFontWeight='bold' bottom=3></fui-tabs>
      </view>
      <view class="page-child-tab">
        <text class="child-tab-item" :class="{'active': item.value === curChildTab}" v-for="item in childTabs" :key="item.name" @click="onChangeChildTab(item.value)">{{ item.name }}
        <text v-show="item.subscript > 0" class="subscript">{{ item.subscript }}</text>
        </text>
        
      </view>
      <view class="order-list">
        <view class="order-item" v-for="item in listData" :key="item.id" @click="listClick(item.id)">
          <view class="order-title" v-if="userType === '2'">订单编号<span>{{ item.code }}</span></view>
          <view class="order-title" v-else>{{ item.supplierName }}</view>
          <view class="order-list-content" v-for="shopItem in item.items" :key="shopItem.id">
            <image :src="shopItem.picUrl" style="width: 132rpx; height: 132rpx; overflow: hidden; border-radius: 16rpx;background-color: #f8f8f8;" mode=""></image>
            <view class="content-right">
              <view class="content-right-title">
                <view class="content-right-title-left">{{ shopItem.spuName }}</view>
                <view class="content-right-title-right"><span>￥</span>{{utils.moneyFormatter(shopItem.price / 100)}}</view>
              </view>
              <view class="content-right-num">x{{shopItem.count}}
              </view>
            </view>
          </view>
          
          <view class="order-list-bottom">
            <span>实付金额：</span>￥{{utils.moneyFormatter(item.totalPrice / 100)}}
          </view>
        </view>
      </view>
      <fui-loadmore :state="moreState"></fui-loadmore>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, inject } from 'vue'
import { onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import pageHeader from '@/components/header'
import pageStatistic from '@/components/statistic'
import supplierApi from '@/api/supplier'
import orderApi from '@/api/order'
import utils from '@/components/firstui/fui-utils'
import { formatValue, formatUnit } from '@/utils/tools'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')
const auth = inject('$auth')

// 用户类型：1-供应链，2-供应商
const { userId, userType } = store.getters

// 默认展示的订单类型
const defaultOrderType = computed(() => {
  if (userType === '1') return '2' // 供应链直供订单
  if (userType === '2') return '1' // 供应商自营订单
})

// 一级标签页
const parentTabs = ref([
  { name: '自营订单', value: '1' },
  { name: '直供订单', value: '2' }
])
const curParentTab = ref(defaultOrderType.value)
const onChangeParentTab = (e) => {
  curParentTab.value = e.value
  onChangeChildTab('0')
}

// 二级标签页
// 0待支付，10待发货，20已发货，30已完成，40已取消
const childTabs = ref([
  { name: '待支付', value: '0' , subscript:0},
  { name: '待发货', value: '10', subscript:0 },
  { name: '待收货', value: '20', subscript:0 },
  { name: '已完成', value: '30', }
])
const curChildTab = ref('0')
const onChangeChildTab = (value) => {
  curChildTab.value = value
  queryParams.value.pageNo = 1
  getOrderList()
}

// 获取统计数据
const { currentTenantId, currentDeptId, companyId } = store.getters
const statisticData = ref([
  {
    name: '订单数量',
    value: 0,
    unit: '单'
  },
  {
    name: '订单销售额',
    value: 0,
    unit: '元'
  }
])
const getStatisticsData = () => {
  try {
    supplierApi.getHomeData({
      zhid: currentTenantId,
      gsid: currentDeptId,
      yhlx: userType
    }).then(res => {
      if (res.code === 0 && res.data) {
        if (res.data.ddtjxx[0]) {
          statisticData.value[0].unit = formatUnit(res.data.ddtjxx[0].val02, '单')
          statisticData.value[0].value = formatValue(res.data.ddtjxx[0].val02)
          const orderTotalMoney = userType === '1' ? res.data.ddtjxx[0].val00 : res.data.ddtjxx[0].val01
          statisticData.value[1].unit = formatUnit(orderTotalMoney, '元')
          statisticData.value[1].value = formatValue(orderTotalMoney)
        }
      } else {
        modal.msgError('获取统计数据失败！')
      }
    })
  } catch(err) {
    modal.msgError('获取统计数据失败！')
  }
}

// 标签页数据
const getOrderStatList = () => {
  try {
    const params = {}
    if (userType === '2') {
      params.supplierId = companyId
    }
    if (auth.hasRole('scm_gysfhzy')) {
      params.adminUserId = userId
    }
    orderApi.getOrderStatList(params).then(res => {
      if (res.code === 0 && res.data) {
        // 待支付 角标
        childTabs.value[0].subscript = parseInt(res.data.dzfCount)
        // 待发货 角标
        childTabs.value[1].subscript = parseInt(res.data.dfhCount)
        // 待收货 角标
        childTabs.value[2].subscript = parseInt(res.data.dshCount)
      } else {
        modal.msgError('获取统计数据失败！')
      }
    })
  } catch(err) {
    modal.msgError('获取统计数据失败！')
  }
}

// 列表底部加载状态，可选值：1-上拉加载 2-正在加载... 3-没有更多了
const moreState = ref(1)

// 获取订单列表
const queryType = computed(() => {
  let type = ''
  if (userType === '1' && curParentTab.value === '1') type = '1' // 供应链自营订单
  if (userType === '1' && curParentTab.value === '2') type = '2' // 供应链直供订单
  if (userType === '2' && curParentTab.value === '1') type = '1' // 供应商自营订单
  return type
})
const queryParams = ref({})
const listData = ref([])
const listApiUrl = computed(() => {
  let apiUrl = ''
  if (queryType.value === '1') apiUrl = 'getSelfOrderList' // 供应链/供应商自营订单
  if (queryType.value === '2') apiUrl = 'getSupplyOrderList' // 供应链直供订单
  return apiUrl
})
const getOrderList = () => {
  try {
    queryParams.value.status = curChildTab.value
    queryParams.value.no = searchValue.value
    if (auth.hasRole('scm_gysfhzy')) {
      queryParams.value.adminUserId = userId
    }
    moreState.value = 2
    modal.loading('加载中...')
    orderApi[listApiUrl.value](queryParams.value).then((res) => {
      modal.closeLoading()
      uni.stopPullDownRefresh()

      if (res.code === 0) {
        const newData = res.data.list.map(item => {
          return {
            ...item,
            code: item.no,
            imgUrl: item.items[0].picUrl,
            title: item.items[0].spuName,
            // price: queryType.value === '1' ? (item.realPrice / item.productCount).toFixed(2) : item.items[0].price,
            price: item.items[0].price,
            num: item.productCount,
            // totalPrice: queryType.value === '1' ? item.realPrice : item.payPrice
            totalPrice: item.payPrice
          }
        })
        if (queryParams.value.pageNo * queryParams.value.pageSize >= res.data.total) {
          moreState.value = 3
        } else {
          moreState.value = 1
        }
        if (queryParams.value.pageNo > 1) {
          listData.value = [...listData.value, ...newData]
        } else {
          listData.value = [...newData]
        }
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch (e) {
    modal.closeLoading()
    uni.stopPullDownRefresh()
  }
}

// 搜索
const searchValue = ref('')
const searchCenter = () => {
  listData.value = []
  getOrderList()
}

onShow(() => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    status: curChildTab.value,
    supplierId: userType === '2' ? companyId : '',
    no: ''
  }
  getOrderList()
  getStatisticsData()
  getOrderStatList()
})

// 上拉加载更多
onReachBottom(() => {
  if (moreState.value == 1) {
    queryParams.value.pageNo++
    getOrderList()
  }
})

// 下拉刷新
onPullDownRefresh(() => {
  queryParams.value.pageNo = 1
  getOrderList()
})

// 点击订单列表
const listClick = (orderId) => {
  const orderStatusObj = childTabs.value.find(item => item.value === curChildTab.value)
  const orderStatus = orderStatusObj.name
  uni.navigateTo({
    url: `/pages/order/view/detail?orderId=${orderId}&orderType=${curParentTab.value}&orderStatus=${encodeURIComponent(orderStatus)}`
  })
}
</script>

<style lang="scss" scoped>
.page-order {
  .page-search {
    position: relative;
    width: 100%;
    margin: 30rpx 0;
    :deep(.fui-input__wrap) {
      padding: 20rpx 24rpx !important;
    }
    span {
      position: absolute;
      z-index: 10;
      right: 0;
      top: 0;
      font-size: 1.25rem;
      color: var(--fui-color-link);
      display: inline-block;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      font-size: 40rpx;
      color: var(--fui-color-link);
    }
  }
  .page-parent-tab {
    position: relative;
    margin-bottom: 30rpx;
    :deep(.fui-tabs__scrollbox) {
      width: fit-content;
    }
    :deep(.fui-tabs__line-short) {
      width: 64rpx !important;
    }
    :deep(.fui-tabs__item) {
      padding-left: 5rpx;
      padding-right: 72rpx;
    }
  }
  .page-child-tab {
    display: flex;
    padding-bottom: 28rpx;
    .child-tab-item {
      height: 48rpx;
      border-radius: 8rpx;
      background: #fff;
      margin-right: 30rpx;
      padding: 0 18rpx;
      line-height: 48rpx;
      white-space: nowrap;
      font-size: 24rpx;
      color: #666666;
      position: relative;
      &.active {
        background: #ecf4ff;
        border: 2rpx solid var(--fui-color-primary);
        font-weight: bold;
        color: var(--fui-color-primary);
      }
      .subscript{
        width: 28rpx;
        height: 28rpx;
        position: absolute;
        top: -4rpx;
        right: -8rpx;
        background: #fb4545;
        border-radius: 100%;
        color: #fff;
        font-size: 16rpx;
        line-height: 28rpx;
        text-align: center;
      }
    }
  }
  .order-list {
    padding-bottom: 15rpx;
    .order-item {
      width: 100%;
      background: #ffffff;
      border-radius: 16rpx;
      box-sizing: border-box;
      margin-bottom: 30rpx;
      overflow: hidden;
      padding: 0 28rpx;
      .order-title {
        height: 78rpx;
        line-height: 78rpx;
        padding: 0 28rpx;
        font-size: 28rpx;
        font-weight: bold;
        color: #333333;
        background: linear-gradient(
          93deg,
          #e9efff 0%,
          rgba(255, 255, 255, 0.05) 80%
        );
        box-sizing: border-box;
        margin: 0 -28rpx;

        span {
          padding-left: 20rpx;
        }
      }

      .order-list-content {
        width: 100%;
        padding: 24rpx 0;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        &:not(:last-child) {
          border-bottom: 2rpx solid #f1f1f1;
        }
        .content-right {
          width: calc(100% - 172rpx);
          font-size: 28rpx;
          font-weight: bold;
          color: #333333;
          line-height: 40rpx;
          .content-right-title {
            display: flex;
            justify-content: space-between;
            
            .content-right-title-left{
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            .content-right-title-right {
              font-size: 36rpx;

              span {
                font-size: 24rpx;
              }
            }
          }
          .content-right-num {
            font-size: 24rpx;
            font-weight: 400;
            color: #666666;
          }
        }

        .right-list {
          display: flex;
          flex-wrap: wrap;

          .right-text {
            width: 50%;
            font-size: 24rpx;
            font-weight: 400;
            color: #999999;
            display: flex;
            align-items: center;
            margin-bottom: 10rpx;

            image {
              padding-right: 10rpx;
            }

            span {
              color: #333333;
            }

            .right-number {
              font-weight: bold;
              color: var(--fui-color-link);
              padding: 0 10rpx;
            }
          }
        }
      }
      .order-list-bottom {
        width: calc(100% - 56rpx);
        padding: 12rpx 0rpx 20rpx;
        margin: 12rpx auto 0;
        font-size: 32rpx;
        font-weight: bold;
        color: #333333;
        text-align: right;
        span {
          font-size: 28rpx;
          color: #666666;
        }
      }
    }
  }
}
</style>
